package com.liry.security.config;

import cn.hutool.captcha.generator.MathGenerator;
import com.liry.security.domain.AuthConstant;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * 自定义的验证码过滤器
 *
 * @author ALI
 * @since 2023/6/10
 */
public class CustomCaptchaFilter extends OncePerRequestFilter {


    public String loginApi;
    private CacheManager cacheManager;
    private MathGenerator mathGenerator;
    private AuthenticationEntryPoint entryPoint;

    public CustomCaptchaFilter(CacheManager cacheManager, MathGenerator mathGenerator, AuthenticationEntryPoint authenticationEntryPoint,
                               String loginApi) {
        this.cacheManager = cacheManager;
        this.mathGenerator = mathGenerator;
        this.entryPoint = authenticationEntryPoint;
        this.loginApi = loginApi;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {
        if (request.getRequestURI().equals(loginApi)) {
            String id = request.getSession().getId();
            String key = AuthConstant.buildCaptchaKey(id);
            Object match = cacheManager.get(key);
            if (match == null) {
                entryPoint.commence(request, response, new BadCredentialsException("验证码过期！"));
                return;
            }
            // 注意这里的验证码参数不是从body里获取的
            if (!mathGenerator.verify(match.toString(), request.getParameter(AuthConstant.CAPTCHA))) {
                entryPoint.commence(request, response, new BadCredentialsException("验证码验证错误！"));
                return;
            }
            // 验证成功删除
            cacheManager.delete(key);
        }
        filterChain.doFilter(request, response);
    }
}
